package controller.specialty;

import entity.SpecialtyEntity;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.SpecialtyService;
import service.impl.SpecialtyServiceImpl;
import controller.student.StudentServlet;
import util.BaseResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/addSpecialtyInfo")
public class AddSpecialtyInfoServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {

            req.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json;charset=UTF-8");
            BufferedReader reader = req.getReader();
            Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {});

            SpecialtyEntity specialty = new SpecialtyEntity();
            specialty.setAcademyId((String) body.get("academyId"));
            specialty.setSpecialtyName((String) body.get("specialtyName"));
            specialty.setSpecialtyCode((String) body.get("specialtyCode"));

            SpecialtyService specialtyService = new SpecialtyServiceImpl();
            specialtyService.addSpecialtyInfo(specialty);

            BaseResult<Void> result = BaseResult.success();

            resp.setContentType("application/json;charset=UTF-8");

            String jsonResponse = objectMapper.writeValueAsString(result);
            resp.getWriter().write(jsonResponse);

        } catch (Exception e) {
            logger.error("新增专业信息错误", e);

            BaseResult<Void> errorResult = BaseResult.failed(500, "新增专业信息失败: " + e.getMessage());

            resp.setContentType("application/json;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            String jsonError = objectMapper.writeValueAsString(errorResult);
            resp.getWriter().write(jsonError);
        }
    }
}
